package com.ems.mapper;

import com.ems.entity.BatteryBoxEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ems.vo.BatteryBoxVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 电池簇 Mapper 接口
 * </p>
 *
 * @author WuZH
 * @since 2024-04-23
 */
@Mapper
public interface BatteryBoxMapper extends BaseMapper<BatteryBoxEntity> {

    @Select ( value = "SELECT *\n" +
            "FROM battery_box_info bbi JOIN (SELECT deviceAddress, max(createTime) createTime FROM battery_box_info GROUP BY deviceAddress) bbii\n" +
            "ON bbi.deviceAddress=bbii.deviceAddress AND bbi.createTime=bbii.createTime ORDER BY bbi.createTime DESC" )
    List<BatteryBoxVo> queryList ( @Param ( "batteryBoxVo" ) BatteryBoxVo batteryBoxVo );

    @Select ( value = "SELECT COUNT(1) FROM battery_box_info bbi" )
    Integer queryCount ( @Param ( "batteryBoxVo" ) BatteryBoxVo batteryBoxVo );


    /**
     * 查询所有BMS在某一天里的最后一组数据
     *
     * @param batteryBoxVo
     * @return
     */
    @Select ( "SELECT * FROM battery_box_info bbi\n" +
            "         JOIN(\n" +
            "    SELECT MAX(createTime) createTime, deviceAddress\n" +
            "    FROM battery_box_info\n" +
            "    WHERE date_format(createTime, '%Y-%m-%d') = date_format(#{batteryBoxVo.createTime}, '%Y-%m-%d')\n" +
            "    GROUP BY deviceAddress) bbii\n" +
            "                  ON bbi.deviceAddress = bbii.deviceAddress\n" +
            "                      AND bbi.createTime = bbii.createTime\n" )
    List<BatteryBoxVo> queryMaxDataForDay ( @Param ( "batteryBoxVo" ) BatteryBoxVo batteryBoxVo );


    /**
     * 查询某个电站当天实时充放电记录
     * @param batteryBoxVo
     * @return
     */
    @Select ( value = "SELECT * FROM battery_box_info bbi\n" +
            "         LEFT JOIN device_info di ON bbi.deviceAddress = di.deviceAddress\n" +
            "WHERE DATE_FORMAT(bbi.createTime, '%Y-%m-%d') = DATE_FORMAT(now(), '%Y-%m-%d')\n" +
            "AND di.stationId=#{batteryBoxVo.stationId}")
    List<BatteryBoxVo> queryStationForDay ( @Param ( "batteryBoxVo" ) BatteryBoxVo batteryBoxVo );

}
